<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="Java 线上常见故障问题排查实战, Java,Linux,Mysql,Redis,HTTP,操作系统,计算机网络,计算机组成原理,数据结构与算法,工具使用,性能优化">
    <meta name="description" content="本网站是个人兴趣爱好，总结分享经验，记录生活点滴的平台，希望在以后的学习旅途中，走出自己的风景。">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>Java 线上常见故障问题排查实战 | 八戒取经路</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.4.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="八戒取经路" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">八戒取经路</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/navigate" class="waves-effect waves-light">
      
      <i class="fas fa-location-arrow" style="zoom: 0.6;"></i>
      
      <span>导航</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">

      
      <i class="fas fa-address-card" style="zoom: 0.6;"></i>
      
      <span>关于</span>
      <i class="fas fa-chevron-down" aria-hidden="true" style="zoom: 0.6;"></i>
    </a>
    <ul class="sub-nav menus_item_child ">
      
      <li>
        <a href="/about">
          
          <i class="fas fa-user-circle" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>关于我</span>
        </a>
      </li>
      
      <li>
        <a href="/aboutme">
          
          <i class="fa fa-user-secret" style="margin-top: -20px; zoom: 0.6;"></i>
          
          <span>Another</span>
        </a>
      </li>
      
    </ul>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">八戒取经路</div>
        <div class="logo-desc">
            
            本网站是个人兴趣爱好，总结分享经验，记录生活点滴的平台，希望在以后的学习旅途中，走出自己的风景。
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/navigate" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-location-arrow"></i>
			
			导航
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="javascript:;">
			
				<i class="fa-fw fas fa-address-card"></i>
			
			关于
			<span class="m-icon"><i class="fas fa-chevron-right"></i></span>
		</a>
            <ul  style="background:  ;" >
              
                <li>

                  <a href="/about " style="margin-left:75px">
				  
				   <i class="fa fas fa-user-circle" style="position: absolute;left:50px" ></i>
			      
		          <span>关于我</span>
                  </a>
                </li>
              
                <li>

                  <a href="/aboutme " style="margin-left:75px">
				  
				   <i class="fa fa fa-user-secret" style="position: absolute;left:50px" ></i>
			      
		          <span>Another</span>
                  </a>
                </li>
              
            </ul>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/0.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">Java 线上常见故障问题排查实战</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Java/">
                                <span class="chip bg-color">Java</span>
                            </a>
                        
                            <a href="/tags/%E6%AD%BB%E9%94%81/">
                                <span class="chip bg-color">死锁</span>
                            </a>
                        
                            <a href="/tags/top/">
                                <span class="chip bg-color">top</span>
                            </a>
                        
                            <a href="/tags/vmstat/">
                                <span class="chip bg-color">vmstat</span>
                            </a>
                        
                            <a href="/tags/%E8%B0%83%E4%BC%98/">
                                <span class="chip bg-color">调优</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-04-18
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    4.6k
                </div>
                

                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>[TOC]</p>
<h1 id="手把手教你定位常见Java性能问题"><a href="#手把手教你定位常见Java性能问题" class="headerlink" title="手把手教你定位常见Java性能问题"></a>手把手教你定位常见Java性能问题</h1><h3 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h3><p>性能优化一向是后端服务优化的重点，但是线上性能故障问题不是经常出现，或者受限于业务产品，根本就没办法出现性能问题，包括笔者自己遇到的性能问题也不多，所以为了提前储备知识，当出现问题的时候不会手忙脚乱，我们本篇文章来模拟下常见的几个<code>Java</code>性能故障，来学习怎么去分析和定位。</p>
<h3 id="预备知识"><a href="#预备知识" class="headerlink" title="预备知识"></a>预备知识</h3><p>既然是定位问题，肯定是需要借助工具，我们先了解下需要哪些工具可以帮忙定位问题。</p>
<p><strong>top命令</strong></p>
<p><code>top</code>命令使我们最常用的 <code>Linux</code> 命令之一，它可以实时的显示当前正在执行的进程的 <code>CPU</code> 使用率，内存使用率等系统信息。<code>top -Hp pid</code> 可以查看线程的系统资源使用情况。</p>
<p><strong>vmstat命令</strong></p>
<p><code>vmstat</code> 是一个指定周期和采集次数的虚拟内存检测工具，可以统计内存，<code>CPU，swap</code> 的使用情况，它还有一个重要的常用功能，用来观察进程的上下文切换。字段说明如下:</p>
<ul>
<li><p><code>r:</code> 运行队列中进程数量（当数量大于 <code>CPU</code> 核数表示有阻塞的线程）</p>
</li>
<li><p><code>b</code>: 等待IO的进程数量</p>
</li>
<li><p><code>swpd</code>: 使用虚拟内存大小</p>
</li>
<li><p><code>free</code>: 空闲物理内存大小</p>
</li>
<li><p><code>buff</code>: 用作缓冲的内存大小(内存和硬盘的缓冲区)</p>
</li>
<li><p><code>cache</code>: 用作缓存的内存大小（CPU和内存之间的缓冲区）</p>
</li>
<li><p><code>si</code>: 每秒从交换区写到内存的大小，由磁盘调入内存</p>
</li>
<li><p><code>so</code>: 每秒写入交换区的内存大小，由内存调入磁盘</p>
</li>
<li><p><code>bi</code>: 每秒读取的块数</p>
</li>
<li><p><code>bo</code>: 每秒写入的块数</p>
</li>
<li><p><code>in</code>: 每秒中断数，包括时钟中断。</p>
</li>
<li><p><code>cs</code>: 每秒上下文切换数。</p>
</li>
<li><p><code>us</code>: 用户进程执行时间百分比(user time)</p>
</li>
<li><p><code>sy</code>: 内核系统进程执行时间百分比(system time)</p>
</li>
<li><p><code>wa: IO</code>等待时间百分比</p>
</li>
<li><p><code>id</code>: 空闲时间百分比</p>
<p><strong>pidstat命令</strong></p>
</li>
</ul>
<p><code>pidstat</code> 是 <code>Sysstat</code> 中的一个组件，也是一款功能强大的性能监测工具，<code>top</code> 和 <code>vmstat</code> 两个命令都是监测进程的内存、<code>CPU</code> 以及 <code>I/O</code> 使用情况，而 pidstat 命令可以检测到线程级别的。<code>pidstat</code>命令线程切换字段说明如下：</p>
<ul>
<li><p><code>UID</code> ：被监控任务的真实用户<code>ID</code>。</p>
</li>
<li><p><code>TGID</code> ：线程组<code>ID</code>。</p>
</li>
<li><p><code>TID</code>：线程<code>ID</code>。</p>
</li>
<li><p><code>cswch/s</code>：主动切换上下文次数，这里是因为资源阻塞而切换线程，比如锁等待等情况。</p>
</li>
<li><p><code>nvcswch/s</code>：被动切换上下文次数，这里指<code>CPU</code>调度切换了线程。</p>
<p><strong>jstack命令</strong></p>
</li>
</ul>
<p><code>jstack</code>是<code>JDK</code>工具命令，它是一种线程堆栈分析工具，最常用的功能就是使用 <code>jstack pid</code> 命令查看线程的堆栈信息，也经常用来排除死锁情况。</p>
<p><strong>jstat 命令</strong></p>
<p>它可以检测<code>Java</code>程序运行的实时情况，包括堆内存信息和垃圾回收信息，我们常常用来查看程序垃圾回收情况。常用的命令是<code>jstat -gc pid</code>。信息字段说明如下：</p>
<ul>
<li><code>S0C</code>：年轻代中 <code>To Survivor</code> 的容量（单位 <code>KB</code>）；</li>
<li><code>S1C</code>：年轻代中 <code>From Survivor</code> 的容量（单位 <code>KB</code>）；</li>
<li><code>S0U</code>：年轻代中 <code>To Survivor</code> 目前已使用空间（单位 <code>KB</code>）；</li>
<li><code>S1U</code>：年轻代中 <code>From Survivor</code> 目前已使用空间（单位 <code>KB</code>）；</li>
<li><code>EC</code>：年轻代中 <code>Eden</code> 的容量（单位 <code>KB</code>）；</li>
<li><code>EU</code>：年轻代中 <code>Eden</code> 目前已使用空间（单位 <code>KB</code>）；</li>
<li><code>OC</code>：老年代的容量（单位 <code>KB</code>）；</li>
<li><code>OU</code>：老年代目前已使用空间（单位 <code>KB</code>）；</li>
<li><code>MC</code>：元空间的容量（单位 <code>KB</code>）；</li>
<li><code>MU</code>：元空间目前已使用空间（单位 <code>KB</code>）；</li>
<li><code>YGC</code>：从应用程序启动到采样时年轻代中 <code>gc</code> 次数；</li>
<li><code>YGCT</code>：从应用程序启动到采样时年轻代中 <code>gc</code> 所用时间 (s)；</li>
<li><code>FGC</code>：从应用程序启动到采样时 老年代<code>（Full Gc）gc</code> 次数；</li>
<li><code>FGCT</code>：从应用程序启动到采样时 老年代代<code>（Full Gc）gc</code> 所用时间 <code>(s)</code>；</li>
<li><code>GCT</code>：从应用程序启动到采样时 <code>gc</code> 用的总时间 (s)。</li>
</ul>
<p><strong>jmap命令</strong></p>
<p><code>jmap</code>也是<code>JDK</code>工具命令，他可以查看堆内存的初始化信息以及堆内存的使用情况，还可以生成<code>dump</code>文件来进行详细分析。查看堆内存情况命令<code>jmap -heap pid</code>。</p>
<p><strong>mat内存工具</strong></p>
<p><code>MAT(Memory Analyzer Tool)</code>工具是 <code>eclipse</code> 的一个插件( <code>MAT</code> 也可以单独使用)，它分析大内存的 <code>dump</code> 文件时，可以非常直观的看到各个对象在堆空间中所占用的内存大小、类实例数量、对象引用关系、利用 <code>OQL</code> 对象查询，以及可以很方便的找出对象 <code>GC Roots</code> 的相关信息。</p>
<p><strong>idea中也有这么一个插件，就是JProfiler</strong>。</p>
<p>相关阅读：</p>
<ol>
<li>《性能诊断利器 <code>JProfiler</code> 快速入门和最佳实践》：<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000017795841">https://segmentfault.com/a/1190000017795841</a></li>
</ol>
<h3 id="模拟环境准备"><a href="#模拟环境准备" class="headerlink" title="模拟环境准备"></a>模拟环境准备</h3><p>基础环境 <code>jdk1.8</code>，采用 <code>SpringBoot</code> 框架来写几个接口来触发模拟场景，首先是模拟 <code>CPU</code> 占满情况</p>
<h3 id="CPU-占满"><a href="#CPU-占满" class="headerlink" title="CPU 占满"></a><code>CPU</code> 占满</h3><p>模拟 <code>CPU</code> 占满还是比较简单，直接写一个死循环计算消耗 <code>CPU</code> 即可。</p>
<pre class=" language-java"><code class="language-java">     <span class="token comment" spellcheck="true">/**
     * 模拟CPU占满
     */</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/cpu/loop"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">testCPULoop</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> InterruptedException <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"请求cpu死循环"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">setName</span><span class="token punctuation">(</span><span class="token string">"loop-thread-cpu"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">int</span> num <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            num<span class="token operator">++</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span>num <span class="token operator">==</span> Integer<span class="token punctuation">.</span>MAX_VALUE<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"reset"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            num <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

    <span class="token punctuation">}</span>Copy to clipboardErrorCopied
</code></pre>
<p>请求接口地址测试<code>curl localhost:8080/cpu/loop</code>,发现 <code>CPU</code> 立马飙升到 <code>100%</code></p>
<p><img src="https://gitee.com/CodeJourney/source_file/raw/master/blog_img/java-performance6.png" alt="img"></p>
<p>通过执行<code>top -Hp 32805</code> 查看<code>Java</code>线程情况</p>
<p><img src="https://gitee.com/CodeJourney/source_file/raw/master/blog_img/java-performance6.png" alt="img"></p>
<p>执行 <code>printf '%x' 32826</code> 获取16进制的线程id，用于<code>dump</code>信息查询，结果为 <code>803a</code>。最后我们执行<code>jstack 32805 |grep -A 20 803a </code>来查看下详细的<code>dump</code>信息。</p>
<p><img src="https://gitee.com/CodeJourney/source_file/raw/master/blog_img/java-performance6.png" alt="img"></p>
<p>这里 <code>dump</code> 信息直接定位出了问题方法以及代码行，这就定位出了 <code>CPU</code> 占满的问题。</p>
<h3 id="内存泄露"><a href="#内存泄露" class="headerlink" title="内存泄露"></a>内存泄露</h3><p>模拟内存泄漏借助了 <code>ThreadLocal</code> 对象来完成，<code>ThreadLocal</code> 是一个线程私有变量，可以绑定到线程上，在整个线程的生命周期都会存在，但是由于<code>ThreadLocal</code> 的特殊性，<code>ThreadLocal</code> 是基于 <code>ThreadLocalMap</code> 实现的，<code>ThreadLocalMap</code> 的 <code>Entry</code> 继承 <code>WeakReference</code>，而 <code>Entry</code>的<code>Key</code>是<code>WeakReference</code> 的封装，换句话说 <code>Key</code> 就是弱引用，弱引用在下次 <code>GC</code> 之后就会被回收，如果 <code>ThreadLocal</code> 在 <code>set</code> 之后不进行后续的操作，因为 <code>GC</code> 会把<code>Key</code>清除掉，但是<code>Value</code>由于线程还在存活，所以<code>Value</code>一直不会被回收，最后就会发生内存泄漏。</p>
<pre class=" language-Java"><code class="language-Java">/**
     * 模拟内存泄漏
     */
    @GetMapping(value = "/memory/leak")
    public String leak() {
        System.out.println("模拟内存泄漏");
        ThreadLocal<Byte[]> localVariable = new ThreadLocal<Byte[]>();
        localVariable.set(new Byte[4096 * 1024]);// 为线程添加变量
        return "ok";
    }Copy to clipboardErrorCopied
</code></pre>
<p>我们给启动加上堆内存大小限制，同时设置内存溢出的时候输出堆栈快照并输出日志。</p>
<pre class=" language-java"><code class="language-java">java <span class="token operator">-</span>jar <span class="token operator">-</span>Xms500m <span class="token operator">-</span>Xmx500m <span class="token operator">-</span>XX<span class="token operator">:</span><span class="token operator">+</span>HeapDumpOnOutOfMemoryError <span class="token operator">-</span>XX<span class="token operator">:</span>HeapDumpPath<span class="token operator">=</span><span class="token operator">/</span>tmp<span class="token operator">/</span>heapdump<span class="token punctuation">.</span>hprof  <span class="token operator">-</span>XX<span class="token operator">:</span><span class="token operator">+</span>PrintGCTimeStamps <span class="token operator">-</span>XX<span class="token operator">:</span><span class="token operator">+</span>PrintGCDetails <span class="token operator">-</span>Xloggc<span class="token operator">:</span><span class="token operator">/</span>tmp<span class="token operator">/</span>heaplog<span class="token punctuation">.</span>log analysis<span class="token operator">-</span>demo<span class="token operator">-</span><span class="token number">0.0</span><span class="token punctuation">.</span><span class="token number">1</span><span class="token operator">-</span>SNAPSHOT<span class="token punctuation">.</span>jar
</code></pre>
<p>启动成功后我们循环执行 <code>100</code> 次,<code>for i in {1..500}; do curl localhost:8080/memory/leak;done</code>,还没执行完毕，系统已经返回 <code>500</code> 错误了。查看系统日志出现了如下异常：</p>
<pre class=" language-java"><code class="language-java">java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>OutOfMemoryError<span class="token operator">:</span> Java heap spaceCopy to clipboardErrorCopied
</code></pre>
<p>我们用<code>jstat -gc pid</code> 命令来看看程序的<code>GC</code>情况。</p>
<p><img src="https://gitee.com/CodeJourney/source_file/raw/master/blog_img/java-performance6.png" alt="img"></p>
<p>很明显，内存溢出了，堆内存经过<code>45</code>次 <code>Full Gc</code> 之后都没释放出可用内存，这说明当前堆内存中的对象都是存活的，有<code>GC Roots</code>引用，无法回收。那是什么原因导致内存溢出呢？是不是我只要加大内存就行了呢？如果是普通的内存溢出也许扩大内存就行了，但是如果是内存泄漏的话，扩大的内存不一会就会被占满，所以我们还需要确定是不是内存泄漏。我们之前保存了堆 <code>Dump</code> 文件，这个时候借助我们的<code>MAT</code>工具来分析下。导入工具选择<code>Leak Suspects Report</code>，工具直接就会给你列出问题报告。</p>
<p><img src="https://gitee.com/CodeJourney/source_file/raw/master/blog_img/java-performance6.png" alt="img"></p>
<p>这里已经列出了可疑的<code>4</code>个内存泄漏问题，我们点击其中一个查看详情。</p>
<p><img src="https://gitee.com/CodeJourney/source_file/raw/master/blog_img/java-performance6.png" alt="img"></p>
<p>这里已经指出了内存被线程占用了接近<code>50M</code>的内存，占用的对象就是<code>ThreadLocal</code>。如果想详细的通过手动去分析的话，可以点击<code>Histogram</code>,查看最大的对象占用是谁，然后再分析它的引用关系，即可确定是谁导致的内存溢出。</p>
<p><img src="https://snailclimb.gitee.io/javaguide/docs/java/images/performance-tuning/java-performance7.png" alt="img"></p>
<p>上图发现占用内存最大的对象是一个<code>Byte</code>数组，我们看看它到底被那个<code>GC Root</code>引用导致没有被回收。按照上图红框操作指引，结果如下图：</p>
<p><img src="https://snailclimb.gitee.io/javaguide/docs/java/images/performance-tuning/java-performance8.png" alt="img"></p>
<p>我们发现<code>Byte</code>数组是被线程对象引用的，图中也标明，<code>Byte</code>数组对像的<code>GC Root</code>是线程，所以它是不会被回收的，展开详细信息查看，我们发现最终的内存占用对象是被<code>ThreadLocal</code>对象占据了。这也和<code>MAT</code>工具自动帮我们分析的结果一致。</p>
<h3 id="死锁"><a href="#死锁" class="headerlink" title="死锁"></a>死锁</h3><p>死锁会导致耗尽线程资源，占用内存，表现就是内存占用升高，<code>CPU</code>不一定会飙升(看场景决定)，如果是直接new线程，会导致JVM内存被耗尽，报无法创建线程的错误，这也是体现了使用线程池的好处。</p>
<pre class=" language-java"><code class="language-java"> ExecutorService service <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor</span><span class="token punctuation">(</span><span class="token number">4</span><span class="token punctuation">,</span> <span class="token number">10</span><span class="token punctuation">,</span>
            <span class="token number">0</span><span class="token punctuation">,</span> TimeUnit<span class="token punctuation">.</span>SECONDS<span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">LinkedBlockingQueue</span><span class="token operator">&lt;</span>Runnable<span class="token operator">></span><span class="token punctuation">(</span><span class="token number">1024</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            Executors<span class="token punctuation">.</span><span class="token function">defaultThreadFactory</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
            <span class="token keyword">new</span> <span class="token class-name">ThreadPoolExecutor<span class="token punctuation">.</span>AbortPolicy</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
   <span class="token comment" spellcheck="true">/**
     * 模拟死锁
     */</span>
    <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span><span class="token string">"/cpu/test"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> String <span class="token function">testCPU</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> InterruptedException <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"请求cpu"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Object lock1 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        Object lock2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Object</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        service<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">DeadLockThread</span><span class="token punctuation">(</span>lock1<span class="token punctuation">,</span> lock2<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"deadLookThread-"</span> <span class="token operator">+</span> <span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nextInt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        service<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">DeadLockThread</span><span class="token punctuation">(</span>lock2<span class="token punctuation">,</span> lock1<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token string">"deadLookThread-"</span> <span class="token operator">+</span> <span class="token keyword">new</span> <span class="token class-name">Random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">nextInt</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> <span class="token string">"ok"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">DeadLockThread</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> Object lock1<span class="token punctuation">;</span>
    <span class="token keyword">private</span> Object lock2<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">DeadLockThread1</span><span class="token punctuation">(</span>Object lock1<span class="token punctuation">,</span> Object lock2<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>lock1 <span class="token operator">=</span> lock1<span class="token punctuation">;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>lock2 <span class="token operator">=</span> lock2<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>lock2<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">+</span><span class="token string">"get lock2 and wait lock1"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                TimeUnit<span class="token punctuation">.</span>MILLISECONDS<span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">2000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
            <span class="token keyword">synchronized</span> <span class="token punctuation">(</span>lock1<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span>Thread<span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">+</span><span class="token string">"get lock1 and lock2 "</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>Copy to clipboardErrorCopied
</code></pre>
<p>我们循环请求接口<code>2000</code>次，发现不一会系统就出现了日志错误，线程池和队列都满了,由于我选择的当队列满了就拒绝的策略，所以系统直接抛出异常。</p>
<pre class=" language-java"><code class="language-java">java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>RejectedExecutionException<span class="token operator">:</span> Task java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>FutureTask<span class="token annotation punctuation">@2760298</span> rejected from java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ThreadPoolExecutor<span class="token annotation punctuation">@7ea7cd51</span><span class="token punctuation">[</span>Running<span class="token punctuation">,</span> pool size <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">,</span> active threads <span class="token operator">=</span> <span class="token number">10</span><span class="token punctuation">,</span> queued tasks <span class="token operator">=</span> <span class="token number">1024</span><span class="token punctuation">,</span> completed tasks <span class="token operator">=</span> <span class="token number">846</span><span class="token punctuation">]</span>Copy to clipboardErrorCopied
</code></pre>
<p>通过<code>ps -ef|grep java</code>命令找出 <code>Java</code> 进程 <code>pid</code>，执行<code>jstack pid</code> 即可出现java线程堆栈信息，这里发现了<code>5</code>个死锁，我们只列出其中一个，很明显线程<code>pool-1-thread-2</code>锁住了<code>0x00000000f8387d88</code>等待<code>0x00000000f8387d98</code>锁，线程<code>pool-1-thread-1</code>锁住了<code>0x00000000f8387d98</code>等待锁<code>0x00000000f8387d88</code>,这就产生了死锁。</p>
<pre class=" language-java"><code class="language-java">Java stack information <span class="token keyword">for</span> the threads listed above<span class="token operator">:</span>
<span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">==</span><span class="token operator">=</span>
<span class="token string">"pool-1-thread-2"</span><span class="token operator">:</span>
        at top<span class="token punctuation">.</span>luozhou<span class="token punctuation">.</span>analysisdemo<span class="token punctuation">.</span>controller<span class="token punctuation">.</span>DeadLockThread2<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>DeadLockThread<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">30</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> waiting to lock <span class="token operator">&lt;</span><span class="token number">0x00000000f8387d98</span><span class="token operator">></span> <span class="token punctuation">(</span>a java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>Object<span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token operator">&lt;</span><span class="token number">0x00000000f8387d88</span><span class="token operator">></span> <span class="token punctuation">(</span>a java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>Object<span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>Executors$RunnableAdapter<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>Executors<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">511</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>FutureTask<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>FutureTask<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">266</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ThreadPoolExecutor<span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span>ThreadPoolExecutor<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1149</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ThreadPoolExecutor$Worker<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>ThreadPoolExecutor<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>Thread<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>Thread<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>
<span class="token string">"pool-1-thread-1"</span><span class="token operator">:</span>
        at top<span class="token punctuation">.</span>luozhou<span class="token punctuation">.</span>analysisdemo<span class="token punctuation">.</span>controller<span class="token punctuation">.</span>DeadLockThread1<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>DeadLockThread<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">30</span><span class="token punctuation">)</span>
        <span class="token operator">-</span> waiting to lock <span class="token operator">&lt;</span><span class="token number">0x00000000f8387d88</span><span class="token operator">></span> <span class="token punctuation">(</span>a java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>Object<span class="token punctuation">)</span>
        <span class="token operator">-</span> locked <span class="token operator">&lt;</span><span class="token number">0x00000000f8387d98</span><span class="token operator">></span> <span class="token punctuation">(</span>a java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>Object<span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>Executors$RunnableAdapter<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>Executors<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">511</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>FutureTask<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>FutureTask<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">266</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ThreadPoolExecutor<span class="token punctuation">.</span><span class="token function">runWorker</span><span class="token punctuation">(</span>ThreadPoolExecutor<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">1149</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>util<span class="token punctuation">.</span>concurrent<span class="token punctuation">.</span>ThreadPoolExecutor$Worker<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>ThreadPoolExecutor<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">624</span><span class="token punctuation">)</span>
        at java<span class="token punctuation">.</span>lang<span class="token punctuation">.</span>Thread<span class="token punctuation">.</span><span class="token function">run</span><span class="token punctuation">(</span>Thread<span class="token punctuation">.</span>java<span class="token operator">:</span><span class="token number">748</span><span class="token punctuation">)</span>

 Found <span class="token number">5</span> deadlocks<span class="token punctuation">.</span>Copy to clipboardErrorCopied
</code></pre>
<h3 id="线程频繁切换"><a href="#线程频繁切换" class="headerlink" title="线程频繁切换"></a>线程频繁切换</h3><p>上下文切换会导致将大量<code>CPU</code>时间浪费在寄存器、内核栈以及虚拟内存的保存和恢复上，导致系统整体性能下降。当你发现系统的性能出现明显的下降时候，需要考虑是否发生了大量的线程上下文切换。</p>
<pre class=" language-java"><code class="language-java"> <span class="token annotation punctuation">@GetMapping</span><span class="token punctuation">(</span>value <span class="token operator">=</span> <span class="token string">"/thread/swap"</span><span class="token punctuation">)</span>
    <span class="token keyword">public</span> String <span class="token function">theadSwap</span><span class="token punctuation">(</span><span class="token keyword">int</span> num<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        System<span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"模拟线程切换"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> num<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token keyword">new</span> <span class="token class-name">Thread</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">ThreadSwap1</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">AtomicInteger</span><span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span><span class="token string">"thread-swap"</span><span class="token operator">+</span>i<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">start</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
        <span class="token keyword">return</span> <span class="token string">"ok"</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ThreadSwap1</span> <span class="token keyword">implements</span> <span class="token class-name">Runnable</span> <span class="token punctuation">{</span>
    <span class="token keyword">private</span> AtomicInteger integer<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token function">ThreadSwap1</span><span class="token punctuation">(</span>AtomicInteger integer<span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>integer <span class="token operator">=</span> integer<span class="token punctuation">;</span>
    <span class="token punctuation">}</span>

    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">run</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
        <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            integer<span class="token punctuation">.</span><span class="token function">addAndGet</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            Thread<span class="token punctuation">.</span><span class="token function">yield</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">//让出CPU资源</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
<span class="token punctuation">}</span>Copy to clipboardErrorCopied
</code></pre>
<p>这里我创建多个线程去执行基础的原子<code>+1</code>操作，然后让出 <code>CPU</code> 资源，理论上 <code>CPU</code> 就会去调度别的线程，我们请求接口创建<code>100</code>个线程看看效果如何，<code>curl localhost:8080/thread/swap?num=100</code>。接口请求成功后，我们执行``vmstat 1 10<code>，表示每</code>1<code>秒打印一次，打印</code>10`次，线程切换采集结果如下：</p>
<pre class=" language-shell"><code class="language-shell">procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free   buff  cache   si   so    bi    bo   in   cs us sy id wa st
101  0 128000 878384    908 468684    0    0     0     0 4071 8110498 14 86  0  0  0
100  0 128000 878384    908 468684    0    0     0     0 4065 8312463 15 85  0  0  0
100  0 128000 878384    908 468684    0    0     0     0 4107 8207718 14 87  0  0  0
100  0 128000 878384    908 468684    0    0     0     0 4083 8410174 14 86  0  0  0
100  0 128000 878384    908 468684    0    0     0     0 4083 8264377 14 86  0  0  0
100  0 128000 878384    908 468688    0    0     0   108 4182 8346826 14 86  0  0  0Copy to clipboardErrorCopied
</code></pre>
<p>这里我们关注<code>4</code>个指标，<code>r</code>,<code>cs</code>,<code>us</code>,<code>sy</code>。</p>
<p><strong>r=100</strong>,说明等待的进程数量是<code>100</code>，线程有阻塞。</p>
<p><strong>cs=800多万</strong>，说明每秒上下文切换了<code>800</code>多万次，这个数字相当大了。</p>
<p><strong>us=14</strong>，说明用户态占用了<code>14%</code>的<code>CPU</code>时间片去处理逻辑。</p>
<p><strong>sy=86</strong>，说明内核态占用了<code>86%</code>的<code>CPU</code>，这里明显就是做上下文切换工作了。</p>
<p>我们通过<code>top</code>命令以及<code>top -Hp pid</code>查看进程和线程<code>CPU</code>情况，发现<code>Java</code>线程<code>CPU</code>占满了，但是线程<code>CPU</code>使用情况很平均，没有某一个线程把<code>CPU</code>吃满的情况。</p>
<pre class=" language-shell"><code class="language-shell">PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND                                                                            
 87093 root      20   0 4194788 299056  13252 S 399.7 16.1  65:34.67 java Copy to clipboardErrorCopied
 PID USER      PR  NI    VIRT    RES    SHR S %CPU %MEM     TIME+ COMMAND                                                                             
 87189 root      20   0 4194788 299056  13252 R  4.7 16.1   0:41.11 java                                                                                
 87129 root      20   0 4194788 299056  13252 R  4.3 16.1   0:41.14 java                                                                                
 87130 root      20   0 4194788 299056  13252 R  4.3 16.1   0:40.51 java                                                                                
 87133 root      20   0 4194788 299056  13252 R  4.3 16.1   0:40.59 java                                                                                
 87134 root      20   0 4194788 299056  13252 R  4.3 16.1   0:40.95 java Copy to clipboardErrorCopied
</code></pre>
<p>结合上面用户态<code>CPU</code>只使用了<code>14%</code>，内核态<code>CPU</code>占用了<code>86%</code>，可以基本判断是<code>Java</code>程序线程上下文切换导致性能问题。</p>
<p>我们使用<code>pidstat</code>命令来看看Java进程内部的线程切换数据，执行<code>pidstat -p 87093 -w 1 10 </code>,采集数据如下：</p>
<pre class=" language-shell"><code class="language-shell">11:04:30 PM   UID       TGID       TID   cswch/s nvcswch/s  Command
11:04:30 PM     0         -     87128      0.00     16.07  |__java
11:04:30 PM     0         -     87129      0.00     15.60  |__java
11:04:30 PM     0         -     87130      0.00     15.54  |__java
11:04:30 PM     0         -     87131      0.00     15.60  |__java
11:04:30 PM     0         -     87132      0.00     15.43  |__java
11:04:30 PM     0         -     87133      0.00     16.02  |__java
11:04:30 PM     0         -     87134      0.00     15.66  |__java
11:04:30 PM     0         -     87135      0.00     15.23  |__java
11:04:30 PM     0         -     87136      0.00     15.33  |__java
11:04:30 PM     0         -     87137      0.00     16.04  |__javaCopy to clipboardErrorCopied
</code></pre>
<p>根据上面采集的信息，我们知道<code>Java</code>的线程每秒切换<code>15</code>次左右，正常情况下，应该是个位数或者小数。结合这些信息我们可以断定<code>Java</code>线程开启过多，导致频繁上下文切换，从而影响了整体性能。</p>
<p><strong>为什么系统的上下文切换是每秒800多万，而 Java 进程中的某一个线程切换才15次左右？</strong></p>
<p>系统上下文切换分为三种情况:</p>
<p>1、多任务：在多任务环境中，一个进程被切换出<code>CPU</code>，运行另外一个进程，这里会发生上下文切换。</p>
<p>2、中断处理：发生中断时，硬件会切换上下文。在 <code>vmstat</code> 命令中是<code>in</code></p>
<p>3、用户和内核模式切换：当操作系统中需要在用户模式和内核模式之间进行转换时，需要进行上下文切换,比如进行系统函数调用。</p>
<p><code>Linux</code> 为每个 <code>CPU</code> 维护了一个就绪队列，将活跃进程按照优先级和等待 <code>CPU</code> 的时间排序，然后选择最需要 <code>CPU</code> 的进程，也就是优先级最高和等待 <code>CPU</code> 时间最长的进程来运行。也就是 <code>vmstat</code> 命令中的<code>r</code>。</p>
<p>那么，进程在什么时候才会被调度到 <code>CPU</code> 上运行呢？</p>
<ul>
<li>进程执行完终止了，它之前使用的 <code>CPU</code> 会释放出来，这时再从就绪队列中拿一个新的进程来运行</li>
<li>为了保证所有进程可以得到公平调度，<code>CPU</code> 时间被划分为一段段的时间片，这些时间片被轮流分配给各个进程。当某个进程时间片耗尽了就会被系统挂起，切换到其它等待 <code>CPU</code> 的进程运行。</li>
<li>进程在系统资源不足时，要等待资源满足后才可以运行，这时进程也会被挂起，并由系统调度其它进程运行。</li>
<li>当进程通过睡眠函数 <code>sleep</code> 主动挂起时，也会重新调度。</li>
<li>当有优先级更高的进程运行时，为了保证高优先级进程的运行，当前进程会被挂起，由高优先级进程来运行。</li>
<li>发生硬件中断时，<code>CPU</code> 上的进程会被中断挂起，转而执行内核中的中断服务程序。</li>
</ul>
<p>结合我们之前的内容分析，阻塞的就绪队列是 <code>100</code> 左右，而我们的<code>CPU</code>只有<code>4</code>核，这部分原因造成的上下文切换就可能会相当高，再加上中断次数是<code>4000</code>左右和系统的函数调用等，整个系统的上下文切换到<code>800</code>万也不足为奇了。<code>Java</code>内部的线程切换才<code>15</code>次，是因为线程使用<code>Thread.yield()</code>来让出<code>CPU</code>资源，但是<code>CPU</code>有可能继续调度该线程，这个时候线程之间并没有切换，这也是为什么内部的某个线程切换次数并不是非常大的原因。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p>本文模拟了常见的性能问题场景，分析了如何定位<code>CPU100%</code>、内存泄漏、死锁、线程频繁切换问题。分析问题我们需要做好两件事，第一，掌握基本的原理，第二，借助好工具。本文也列举了分析问题的常用工具和命令，希望对你解决问题有所帮助。当然真正的线上环境可能十分复杂，并没有模拟的环境那么简单，但是原理是一样的，问题的表现也是类似的，我们重点抓住原理，活学活用，相信复杂的线上问题也可以顺利解决。</p>
<p><a target="_blank" rel="noopener" href="https://snailclimb.gitee.io/javaguide/#/./docs/java/%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E4%BD%A0%E5%AE%9A%E4%BD%8D%E5%B8%B8%E8%A7%81Java%E6%80%A7%E8%83%BD%E9%97%AE%E9%A2%98">文章引用地址</a></p>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">八戒取经路</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://codejourney.gitee.io/2021/04/18/Java-%E7%BA%BF%E4%B8%8A%E5%B8%B8%E8%A7%81%E6%95%85%E9%9A%9C%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5%E5%AE%9E%E6%88%98/">https://codejourney.gitee.io/2021/04/18/Java-%E7%BA%BF%E4%B8%8A%E5%B8%B8%E8%A7%81%E6%95%85%E9%9A%9C%E9%97%AE%E9%A2%98%E6%8E%92%E6%9F%A5%E5%AE%9E%E6%88%98/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">八戒取经路</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Java/">
                                    <span class="chip bg-color">Java</span>
                                </a>
                            
                                <a href="/tags/%E6%AD%BB%E9%94%81/">
                                    <span class="chip bg-color">死锁</span>
                                </a>
                            
                                <a href="/tags/top/">
                                    <span class="chip bg-color">top</span>
                                </a>
                            
                                <a href="/tags/vmstat/">
                                    <span class="chip bg-color">vmstat</span>
                                </a>
                            
                                <a href="/tags/%E8%B0%83%E4%BC%98/">
                                    <span class="chip bg-color">调优</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2021/04/20/%E3%80%90JVM%E3%80%91-%E4%BB%8EJVM%E7%9A%84%E8%A7%92%E5%BA%A6%E7%9C%8Bjava%E6%98%AF%E5%A6%82%E4%BD%95%E8%BF%90%E8%A1%8C%E7%9A%84%EF%BC%88%E7%AC%AC%E4%B8%80%E7%AF%87%EF%BC%89/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/0.jpg" class="responsive-img" alt="【JVM】 从JVM的角度看java是如何运行的（第一篇）">
                        
                        <span class="card-title">【JVM】 从JVM的角度看java是如何运行的（第一篇）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-04-20
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            八戒取经路
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/JVM/">
                        <span class="chip bg-color">JVM</span>
                    </a>
                    
                    <a href="/tags/JRE/">
                        <span class="chip bg-color">JRE</span>
                    </a>
                    
                    <a href="/tags/JDK/">
                        <span class="chip bg-color">JDK</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2021/04/17/Java-%E6%95%85%E9%9A%9C%E8%AF%8A%E6%96%AD%E5%AE%9E%E6%88%98/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="Java 故障诊断实战">
                        
                        <span class="card-title">Java 故障诊断实战</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-04-17
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-user fa-fw"></i>
                            八戒取经路
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                    <a href="/tags/JVM/">
                        <span class="chip bg-color">JVM</span>
                    </a>
                    
                    <a href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
                        <span class="chip bg-color">性能优化</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2019-2021</span>
            
            <span id="year">2019</span>
            <a href="/about" target="_blank">八戒取经路</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/blinkfox" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:843355928@qq.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=843355928" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 843355928" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
